/*
 * hanabiratasksendpost.cpp
 *
 *  Created on: Sep 28, 2011
 *      Author: anonovermind <anonovermind@gmail.com>
 */

#include "hanabiratasksendpost.h"
#include "hanabiraagent.h"
#include <sstream>

namespace Wishmaster {

template <class T>
static std::string to_string(const T& t)
{
	std::ostringstream oss;
	oss << t;
	return oss.str();
}


HanabiraTaskSendPost::HanabiraTaskSendPost(const PostDescriptor& post, const QString& captcha,
		Wishmaster2::Network::RequestManager* requestManager, const QString& msg, HanabiraAgent* agent) :
		TaskSendPost(post, captcha, requestManager, msg),
		m_post(post),
		m_captcha(captcha),
		m_agent(agent)
{

}

HanabiraTaskSendPost::~HanabiraTaskSendPost() {
}

Wishmaster2::Network::RequestPtr HanabiraTaskSendPost::makeRequest(const PostDescriptor & post, const QString & captcha, Wishmaster2::Network::RequestManager *requestManager)
{
	QDateTime t = QDateTime::currentDateTime();
	QString script = post.board + "post/new.xhtml";
	if(post.attachments.count() > 0)
		script += QString("?X-Progress-ID=%1%2").arg(t.toTime_t()).arg("000000");

	Wishmaster2::Network::Url url(std::string("http://") + post.parent_thread.chanName().toStdString() + script.toStdString());
	Wishmaster2::Network::RequestPtr request = requestManager->createRequest(url);
	request->setParameter("http:method", "POST");
	request->setParameter("thread_id", post.parent_thread.threadStringId().toStdString());
	request->setParameter("task", "post");
	request->setParameter("scroll_to", post.parent_thread.threadStringId().toStdString());
	request->setParameter("name", std::string(post.name.toUtf8().constData()));
	if(post.sage)
		request->setParameter("sage", "checked");
	request->setParameter("subject", std::string(post.topic.toUtf8().constData()));
	request->setParameter("message", std::string(post.text.toUtf8().constData()));
	request->setParameter("captcha", std::string(captcha.toUtf8().constData()));
	request->setParameter("password", std::string(post.password.toUtf8().constData()));


	if(post.attachments.count() > 0)
	{
		request->setParameter("post_files_count", to_string(post.attachments.count()));
		for(int i = 0; i < post.attachments.count(); i++)
		{
			m_agent->addAttachments(request, post.attachments.at(i), QString("file_%1").arg(i + 1));
			request->setParameter(QString("file_%1_rating").arg(i + 1).toStdString(), std::string(post.attachments.at(i).rating.toUtf8().constData()));
		}
	}
	else
	{
		request->setParameter("post_files_count", to_string(post.attachments.count()));
		m_agent->addAttachments(request, AttachmentDescriptor(), "file_1");
		request->setParameter("file_1_rating", "SFW");
	}

	request->setParameter("goto", "board");

	QString referer = QString("http://%1%2res/%3.xhtml").arg(post.parent_thread.chanName()).arg(post.board).arg(post.parent_thread.threadNumericId());
	request->setParameter("http:referer", referer.toStdString());
	return request;
}

} /* namespace Wishmaster */
